-module ( clientObject ).
-export ( [start/3, changeClientObjectId/2] ).

-record( kinState, {} ).

-record( state, { world, clientGate, kinObj, id } ).



start( WorldPid, ClientGatePid, KinWorld ) when is_pid(WorldPid), is_pid(ClientGatePid), is_pid(KinWorld) ->
  F = fun() ->
    KinState = #kinState{},
    Pos = {0.0, 0.0, 0.0},
    Vel = {0.0, 0.0, 0.0},
    KinObj = kinematics:newObject( KinWorld, Pos, Vel, KinState, fun kinematicsUpdate/4, fun kinematicsMsg/4 ),
    
    S = #state{ world=WorldPid, clientGate=ClientGatePid, kinObj=KinObj },
    timer:send_after( 100, tick ),
    loop( S )
  end,
  spawn_link( F ).
  



changeClientObjectId( ClientObjectPid, NewId ) ->
  ClientObjectPid ! { change_id, self(), NewId },
  receive
    { id_changed_ok, ClientObjectPid } -> ok
  end.


  
loop( State ) ->
  receive
    { change_id, SrcPid, NewId } ->
      SrcPid ! { id_changed_ok, self() },
      loop( State#state{ id=NewId } );
      
    { client_pos, { X, Y, Z } } ->
      error_logger:info_msg( "Received pos: ~p\n", [{ X, Y, Z }] ),
      loop( State );
      
    tick ->
      tick( State );
    
    Msg ->
      error_logger:error_msg( "Received unexpected message:\n~p\n", [Msg] ),
      loop( State )
  end.



tick( State ) ->
  error_logger:info_msg( "Cl obj ~p tick\n", [State#state.id] ),
  timer:send_after( 100, tick ),
  loop( State ).

  
kinematicsUpdate( State = #kinState{}, Pos, Vel, _DT ) ->
  %[ kinematics:ctrlObj( Pid, { object_pos_upd, self(), Pos } ) || Pid <- State#target.posCast ],
  { continue, State, Pos, Vel }.



kinematicsMsg( State = #kinState{}, Msg, Pos, Vel ) ->
  error_logger:info_msg( "Kin msg: ~p\n", [Msg] ),
  case Msg of
    _X ->
      { continue, State, Pos, Vel }
  end.
